<?php
/**
 * Created by PhpStorm.
 * Date: 2018/4/23
 * Time: 下午10:32
 * qq: 1067713962
 */
namespace app\home\controller;
use think\Controller;
use think\Db;
class Wx extends Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->assign('con', 'a');
        $Config = db('config')->find();
        $this->assign('config',$Config);
    }
    public function index()
    {
        $trade=input('get.trade');
        $val=Db::name('buy')
            ->where('trade',$trade)
            ->find();
        if($val){
            //微信判断
            if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ) {
                return view();
            }
             $data['WIDout_trade_no']=$trade;
             $data['WIDsubject']="产品购买";
             $this->alipay($data);
        }else{
            $this->error('订单号错误');
        }
    }
    //订单号生成
    public function str_rand($length = 32, $char = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') {
        if(!is_int($length) || $length < 0) {
            return false;
        }
        $string = '';
        for($i = $length; $i > 0; $i--) {
            $string .= $char[mt_rand(0, strlen($char) - 1)];
        }

        return $string;
    }
    //购买
    public function shiti_buy(){
        if(!session('user_id')){
            $this->redirect('Login/index');
        }
        //订单描述
        $data['trade']=$this->str_rand();
        $data['price']=6000;
        $data['uid']=session('user_id');
        //添加订单
        $res=Db::name('shiyi_trade')
              ->insert($data);
        $this->redirect('/Wx/shiti_alipay?trade='.$data['trade']);
    }
    public function shiti_alipay(){
        $trade=input('get.trade');
        $res=Db::name('shiyi_trade')
            ->where('trade',$trade)
            ->find();
        if($res){
            //微信判断
            if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') == false ) {
                return view();
            }
            $data['WIDout_trade_no']=$trade;
            $data['WIDsubject']="实体店扶持名额";
            $this->alipay($data);
        }else{
            $this->error('订单号错误');
        }
    }
    public final function alipay($post)
    {
        //商户订单号，商户网站订单系统中唯一订单号，必填
        $out_trade_no = $post['WIDout_trade_no'];
        //订单名称，必填
        $subject = $post['WIDsubject'];
        //付款金额，必填
        $pro = Db::name('buy')->where('trade', $post['WIDout_trade_no'])->value('price');
        $total_amount = $pro;
        session('feel',$total_amount);
        //商品描述，可空
        $body = '';
        //超时时间
        $timeout_express = "1m";
        $config = $this->Config();
        $payRequestBuilder = new \AlipayTradeWapPayContentBuilder();
        $payRequestBuilder->setBody($body);
        $payRequestBuilder->setSubject($subject);
        $payRequestBuilder->setOutTradeNo($out_trade_no);
        $payRequestBuilder->setTotalAmount($total_amount);
        $payRequestBuilder->setTimeExpress($timeout_express);
        $payResponse = new \AlipayTradeService($config);
        $result = $payResponse->wapPay($payRequestBuilder, $config['return_url'], $config['notify_url']);
        echo $result;
        die;
    }
    public function returndataurl()
    {
        //跳转到订单页面
        $this->redirect('personal/tou');
        die;

    }

    //异步函数
    public function notifydataurl()
    {
        die;
        $trade = input('post.out_trade_no');
        //交易状态
        $status = input('post.trade_status');
        $total=input('post.total_amount');
        if ($status == 'TRADE_SUCCESS') {
            //search订单
            $pro = Db::name('buy')->where('trade', $trade)->field('b_buy,uid,price')->find();
            //订单转化为小数格式
            $num=$pro['price'];
            $format_num = sprintf("%.2f",$num);
            //检验回调价格是否一致
            if($format_num!==$total||!$pro){
                echo 'fail';
                die;
            }
            $Money = $pro['price'];
            $id = $pro['uid'];
            //订单status检测
            if ($pro['b_buy'] == 1) {
                echo 'success';
                die;
            } else {
                //业绩操作
                $FaId = Db::name('mumber')->where('uid',$id)->find();
                //用户自身业绩增加（总业绩、当天业绩）
                //总业绩用户自身增加
                $u_yeji=Db::name('mumber_team')
                    ->where('uid',$FaId['uid'])
                    ->value('yeji');
                $yeji=[
                    'yeji'=>$Money+$u_yeji,
                ];
                Db::name('mumber_team')
                    ->where('uid',$FaId['uid'])
                    ->update($yeji);

                //用户本身当天业绩增加
                $d_yeji=Db::name('mumber_team')
                    ->where('uid',$FaId['uid'])
                    ->value('d_yeji');
                $d_yejis=[
                    'd_yeji'=>$Money+$d_yeji,
                ];
                Db::name('mumber_team')
                    ->where('uid',$FaId['uid'])
                    ->update($d_yejis);
                //改变订单状态
                Db::name('buy')->where('trade', $trade)->setField('b_buy', 1);

                //产品数量减少
                $project = Db::name('product')->where('product_price', $Money)->find();
                $nums = $project['product_nums'] - 1;
                Db::name('product')->where('product_price', $Money)->setField('product_nums', $nums);
                //更改产品状态
                if ($nums <= 0) {
                    Db::name('product')->where('product_price', $Money)->setField('product_status', 2);
                }
                //改变首购状态
                if ($FaId['status']==0) {
                    //如果自己状态为为投资状态改为投资状态
                    Db::name('mumber')->where('uid', $id)->setField('status', 1);
                    //父级用户直推加1
                    Db::name('mumber_team')->where('uid',$FaId['fid'])->setInc('tayextension',1);
                }
                //用户自身投资记录增长
                Db::name('mumber')->where('uid', $id)->setInc('acc', $Money);
                //股权增加
                Db::name('mumber')->where('uid',$id)->setInc('guquan',$project['free_data']);
                //积分增加
                Db::name('mumber')->where('uid',$id)->setInc('jifen',$project['free_data']);
                //添加订单记录
                Db::name('trade')->insert([
                    'uid'=> $id,
                    'trade_text' =>$Money.'元购买'.$project['free_data']."份股权赠".$project['free_data']."积分",
                    'trade_status' => 1,
                    'uptime' => time(),
                    'trade_money' => $Money,
                    'trade'=>$trade
                ]) ;
                //佣金按比例增加
                $MoneyArr = array();
                //check订单是否为秒反
                $M_miao = Db::name('buy')->where('trade', $trade)->find();
                if($M_miao['is_miaofan']){
                    $leve = Db::name('leve')->find();
                    $leve_rand=40;
                }else{
                    $leve = Db::name('leve')->find();
                    $leve_rand=40;
                }

                unset($leve['id']);
                foreach ($leve as $k => $v) {
                    $MoneyArr[] = sprintf("%.2f", ($v / 100) * $Money);
                }
                //查询所有大于自己的ID
                $UserArr = Db::name('mumber')->where("uid","<", $id)->select();
                (new Gettree())->getFaTree($UserArr,$MoneyArr,$leve_rand,$FaId['fid'],$Money);
                echo 'success';
                die;
            }
        }
        echo 'fail';
        die;
    }

    /**
     * 支付宝配置
     * @return array
     */
    private function Config()
    {
        $Durl = Db::name('url')->where("status",2)->find();
        //支付宝信息
        $pay = Db::name('pay')->find();
        $appId=$pay['appid'];
        return array(
            //应用ID,您的APPID。
            'app_id' => "{$appId}",
            //商户私钥，您的原始格式RSA私钥
            'merchant_private_key' => "{$pay['private']}",
            //异步通知地址
            'notify_url' => "http://" . $Durl['url'] . "/home/Buy/notifydataurl",
            //同步跳转
            'return_url' => "http://" . $Durl['url'] . "/home/Buy/returndataurl",
            //编码格式
            'charset' => "UTF-8",
            //签名方式
            'sign_type' => "RSA2",
            //支付宝网关
            'gatewayUrl' => "https://openapi.alipay.com/gateway.do",
            //支付宝公钥,查看地址：https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
            'alipay_public_key' => "{$pay['app_public']}",
        );
    }
}
